package com.gydz.gydzbaseframeworkboot.SgsE.controller;

import com.gydz.gydzbaseframeworkboot.Common.utils.export.ExcelUtil;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageParam;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.TableDataInfo;
import com.gydz.gydzbaseframeworkboot.Common.utils.result.ResultUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.sqlUtil.domain.TableSelect;
import com.gydz.gydzbaseframeworkboot.Common.utils.sqlUtil.service.SqlUtilsService;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.EInterfaceHo;
import com.gydz.gydzbaseframeworkboot.SgsE.service.EInterfaceHoService;
import com.gydz.gydzbaseframeworkboot.SystemControl.utils.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/EInterfaceHo")
public class EInterfaceHoController {

    private static final Logger log = LoggerFactory.getLogger(EInterfaceHoController.class);

    @Autowired
    private EInterfaceHoService eInterfaceHoService;

    @Autowired
    private SqlUtilsService sqlUtilsService;

    @ResponseBody
    @Log(remark = "查询切换业务")
    @PostMapping("/list")
    public void list(HttpServletResponse httpServletResponse, @ModelAttribute("eInterfaceHo") EInterfaceHo eInterfaceHo) throws IOException {

        TableSelect tableSelect = new TableSelect();
        tableSelect.setTableSchema("ss7");  // 修改为实际的数据库schema
        tableSelect.setPrefix("e_ho_");      // 修改为切换业务表前缀
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        // 时间范围校验
        if(eInterfaceHo.getStartTime() == null){
            ResultUtils result = ResultUtils.fail("查询切换业务失败,请选择查询时间范围");
            ResultUtils.responseResult(httpServletResponse, result);
            return;
        } else {
            tableSelect.setDateMin(dateFormat.format(eInterfaceHo.getStartTime()));
        }
        if(eInterfaceHo.getEndTime() == null){
            eInterfaceHo.setEndTime(new Date());
        }
        tableSelect.setDateMax(dateFormat.format(eInterfaceHo.getEndTime()));

        // 获取表列表
        List<String> tableList = sqlUtilsService.selectTabeName(tableSelect);
        if(tableList.isEmpty()){
            ResultUtils result = ResultUtils.fail("没有该时间范围的表");
            ResultUtils.responseResult(httpServletResponse, result);
            return;
        }

        // 分页查询
        PageUtils.startPage(new PageParam(eInterfaceHo.getiDisplayStart(),
                eInterfaceHo.getiDisplayLength(),
                eInterfaceHo.getsSortDir(),
                eInterfaceHo.getsSortCol()));
        eInterfaceHo.setTableNameList(tableList);
        List<EInterfaceHo> list = eInterfaceHoService.selectEInterfaceHoList(eInterfaceHo);
        list.forEach(this::convertEnums);
        TableDataInfo tableDataInfo = PageUtils.getDataTable(list);

        ResultUtils result = ResultUtils.succ(200, "查询切换业务成功", tableDataInfo);
        ResultUtils.responseResult(httpServletResponse, result);
    }

    @ResponseBody
    @Log(remark = "导出切换业务")
    @RequestMapping("/exportData")
    public void exportData(HttpServletRequest request,
                           @ModelAttribute("eInterfaceHo") EInterfaceHo eInterfaceHo,
                           HttpServletResponse response) throws IOException {

        TableSelect tableSelect = new TableSelect();
        tableSelect.setTableSchema("ss7");
        tableSelect.setPrefix("e_ho_");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        try {
            // 时间范围校验
            if(eInterfaceHo.getStartTime() == null){
                ResultUtils result = ResultUtils.fail("请选择查询开始时间");
                ResultUtils.responseResult(response, result);
                return;
            } else {
                tableSelect.setDateMin(dateFormat.format(eInterfaceHo.getStartTime()));
            }
            if(eInterfaceHo.getEndTime() == null){
                eInterfaceHo.setEndTime(new Date());
            }
            tableSelect.setDateMax(dateFormat.format(eInterfaceHo.getEndTime()));

            // 获取表列表
            List<String> tableList = sqlUtilsService.selectTabeName(tableSelect);
            if(tableList.isEmpty()){
                ResultUtils result = ResultUtils.fail("没有该时间范围的表");
                ResultUtils.responseResult(response, result);
                return;
            }

            // 设置查询参数
            eInterfaceHo.setsSortCol("");
            eInterfaceHo.setTableNameList(tableList);
            List<EInterfaceHo> list = eInterfaceHoService.selectEInterfaceHoList(eInterfaceHo);

            // 定义导出配置
            String[] excelHeader = {
                    "会话ID", "大会话ID", "协议类型", "开始时间", "结束时间",
                     "OPC", "DPC", "源TID", "目标TID",
                    "主叫IMSI", "被叫IMSI", "主叫号码", "被叫号码", "主叫GT", "被叫GT",
                    "主叫机车号", "被叫机车号", "主叫车次", "被叫车次", "主叫SSN", "被叫SSN",
                    "SCCP原因", "TCAP原因", "SCCP原因类型", "TCAP原因类型", "操作码",
                    "错误码", "错误原因", "板号", "原小区", "目标小区", "切换类型",
                    "切换原因", "切换结果", "失败原因", "RR原因"
            };

            String[] ds_titles = {
                    "biSessID", "biBigSessID", "uintProtoTypeID",
                    "dtSTime", "dtETime", "intOpc", "intDpc", "biStid", "biDtid", "vcCallingImsi",
                    "vcCalledImsi", "vcCallingNumber", "vcCalledNumber", "vcCallingGT",
                    "vcCalledGT", "vcCallingTrainID", "vcCalledTrainID", "vcCallingTrainNo",
                    "vcCalledTrainNo", "uintCallingSSN", "uintCalledSSN", "uintSccpCause",
                    "uintTcapCause", "uintSccpCauseClass", "uintTcapCauseReason", "uintOpCode",
                    "uintErrCode", "uintErrReason", "intCardPort", "intOrigLacCi",
                    "intDestLacCi", "intHoType", "intHoCause", "intHoResult", "intFailedCause",
                    "intRRCause"
            };

            int[] widths = new int[excelHeader.length];
            Arrays.fill(widths, 256 * 18);  // 统一列宽
            widths[4] = widths[5] = 256 * 24; // 时间列加宽

            int[] ds_format = new int[excelHeader.length];
            Arrays.fill(ds_format, 2); // 默认文本格式
            ds_format[4] = ds_format[5] = 1; // 时间列使用日期格式

            // 准备数据
            List<Map<String, Object>> data = new ArrayList<>();
            if (list != null && !list.isEmpty()) {
                SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (EInterfaceHo item : list) {
                    Map<String, Object> map = new HashMap<>();

                    // 基础字段
                    map.put("biSessID", item.getBiSessID());
                    map.put("biBigSessID", item.getBiBigSessID());
//                    map.put("uintInterfaceID", convertInterfaceType(item.getUintInterfaceID()));
                    map.put("uintProtoTypeID", convertProtoType(item.getUintProtoTypeID()));

                    // 时间处理
                    map.put("dtSTime", item.getDtSTime() != null ? timeFormat.format(item.getDtSTime()) : "");
                    map.put("dtETime", item.getDtETime() != null ? timeFormat.format(item.getDtETime()) : "");

                    // 其他字段
                    map.put("intYear", item.getIntYear());
                    map.put("intMonth", item.getIntMonth());
                    map.put("intDay", item.getIntDay());
                    map.put("intHour", item.getIntHour());
                    map.put("intMinute", item.getIntMinute());
                    map.put("intOpc", item.getIntOpc());
                    map.put("intDpc", item.getIntDpc());
                    map.put("biStid", item.getBiStid());
                    map.put("biDtid", item.getBiDtid());
                    map.put("vcCallingImsi", item.getVcCallingImsi());
                    map.put("vcCalledImsi", item.getVcCalledImsi());
                    map.put("vcCallingNumber", item.getVcCallingNumber());
                    map.put("vcCalledNumber", item.getVcCalledNumber());
                    map.put("vcCallingGT", item.getVcCallingGT());
                    map.put("vcCalledGT", item.getVcCalledGT());
                    map.put("vcCallingTrainID", item.getVcCallingTrainID());
                    map.put("vcCalledTrainID", item.getVcCalledTrainID());
                    map.put("vcCallingTrainNo", item.getVcCallingTrainNo());
                    map.put("vcCalledTrainNo", item.getVcCalledTrainNo());
                    map.put("uintCallingSSN", item.getUintCallingSSN());
                    map.put("uintCalledSSN", item.getUintCalledSSN());
                    map.put("uintSccpCause", item.getUintSccpCause());
                    map.put("uintTcapCause", item.getUintTcapCause());
                    map.put("uintSccpCauseClass", item.getUintSccpCauseClass());
                    map.put("uintTcapCauseReason", item.getUintTcapCauseReason());
                    map.put("uintOpCode", item.getUintOpCode());
                    map.put("uintErrCode", item.getUintErrCode());
                    map.put("uintErrReason", item.getUintErrReason());
                    map.put("intCardPort", item.getIntCardPort());
                    map.put("intOrigLacCi", item.getIntOrigLacCi());
                    map.put("intDestLacCi", item.getIntDestLacCi());
                    map.put("intHoType", convertHoType(item.getIntHoType()));
                    map.put("intHoCause", item.getIntHoCause());
                    map.put("intHoResult", convertHoResult(item.getIntHoResult()));
                    map.put("intFailedCause", item.getIntFailedCause());
                    map.put("intRRCause", item.getIntRRCause());

                    data.add(map);
                }
            }

            // 生成文件名
            SimpleDateFormat fileFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "E接口切换业务数据_" + fileFormat.format(new Date());

            // 执行导出
            ExcelUtil.export(fileName, "切换业务明细", excelHeader,
                    ds_titles, ds_format, widths, data, request, response);

        } catch (Exception e) {
            log.error("导出切换业务数据失败", e);
            ResultUtils result = ResultUtils.fail("导出失败：" + e.getMessage());
            ResultUtils.responseResult(response, result);
        }
    }

    // 枚举转换方法
    private void convertEnums(EInterfaceHo ho) {
        if (ho == null) return;

        // 接口类型转换
        ho.setUintInterfaceIDDesc(convertInterfaceType(ho.getUintInterfaceID()));

        // 协议类型转换
        ho.setUintProtoTypeIDDesc(convertProtoType(ho.getUintProtoTypeID()));

        // 切换类型转换
        ho.setIntHoTypeDesc(convertHoType(ho.getIntHoType()));

        // 切换结果转换
        ho.setIntHoResultDesc(convertHoResult(ho.getIntHoResult()));
    }

    // 接口类型枚举转换
    private String convertInterfaceType(Short type) {
        if (type == null) return "";
        switch (type) {
            case 0: return "A";
            case 1: return "C/D";
            case 2: return "E";
            case 3: return "F";
            case 4: return "G";
            case 5: return "L";
            case 6: return "Gr";
            default: return "未知类型";
        }
    }

    // 协议类型枚举转换
    private String convertProtoType(Short type) {
        if (type == null) return "";
        switch (type) {
            case 0: return "MAP协议";
            case 1: return "CAP协议";
            case 2: return "ISUP协议";
            case 3: return "BICC协议";
            case 4: return "H248协议";
            case 5: return "BSSAP协议";
            case 6: return "LAPDm协议";
            case 7: return "Q731协议";
            default: return "未知协议";
        }
    }

    // 切换类型枚举转换
    private String convertHoType(Byte type) {
        if (type == null) return "";
        switch (type) {
            case 0: return "内部切换";
            case 1: return "外部切换";
            default: return "未知切换类型";
        }
    }

    // 切换结果枚举转换
    private String convertHoResult(Byte result) {
        if (result == null) return "";
        switch (result) {
            case 0: return "失败";
            case 1: return "正常";
            default: return "未知结果";
        }
    }
}